package com.demo.scheduled;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.demo.exetion.MainExection;
import com.demo.model.MovieNumberSession;
import com.demo.service.MovieNumberSessionService;
import com.demo.utils.CommonUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@Configuration      //1.主要用于标记配置类，兼备Component的效果。
@EnableScheduling   // 2.开启定时任务,可以加在启动类上
public class ScheduledTask {

    @Resource
    private MovieNumberSessionService movieNumberSessionService;

    @Autowired
    private RedisTemplate<String, Object> ort;

    //场次状态更新任务
    @Scheduled(cron = "0 */60 * * * ?")
    public void fieldStatus() throws MainExection {
        System.out.println("场次状态定时任务开始执行");
        //获取所有的场次
        List<MovieNumberSession> list = movieNumberSessionService.list();
        //获取当时的时间
        LocalDateTime localDateTime = CommonUtil.dataLocalDatePares();
        //100次一循环插入
        int number=0;
        //判断场次状态
        List<MovieNumberSession> movieNumberSessionList=new ArrayList<>();
        for (MovieNumberSession movieNumberSession : list) {
            if (localDateTime.isAfter(movieNumberSession.getEndTime())){
                movieNumberSession.setStart(2);
                number++;
            }else if (localDateTime.isBefore(movieNumberSession.getEndTime())){
                movieNumberSession.setStart(0);
                number++;
            }else if (localDateTime.isBefore(movieNumberSession.getEndTime()) && localDateTime.isAfter(movieNumberSession.getEndTime())){
                movieNumberSession.setStart(1);
                number++;
            }
            movieNumberSessionList.add(movieNumberSession);
            if (number==100){
                boolean b = movieNumberSessionService.updateBatchById(movieNumberSessionList);
                if (!b) throw new MainExection(500,"修改场次状态失败");
                number=0;
                movieNumberSessionList.clear();
            }
        }
        if (number!=0){
            boolean b = movieNumberSessionService.updateBatchById(movieNumberSessionList);
            if (!b) throw new MainExection(500,"修改场次状态失败");
        }
        System.out.println("场次状态定时任务执行完毕");
    }


}
